<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>TaskInfo</title>
</head>
<body>
<div id="toolbar">
    <div class="btn-group" data-toggle="buttons">
        <label class="btn btn-default active">
            <input type="radio" name="succFlag" value="0" onchange="refreshTable()"> 执行中
        </label>
        <label class="btn btn-default">
            <input type="radio" name="succFlag" value="1" onchange="refreshTable()"> 执行成功
        </label>
    </div>
    <button type="button" id="execBtn" class="btn btn-primary" onclick="execute()">执行</button>
</div>
<table id="taskInfoTable"></table>
<script type="text/javascript">
    $(function() {
        $("input[name='succFlag']").get(0).checked=true;
        execBtnDisplay();
        initTable();
    });
    function execBtnDisplay() {
        var succFlag = $("input[name='succFlag']:checked").val();
        if ('0' === succFlag) {
            $("#execBtn").show();
        } else {
            $("#execBtn").hide();
        }
    }
    function refreshTable() {
        execBtnDisplay();
        $('#taskInfoTable').bootstrapTable('refresh');
    }
    function initTable(){
        $('#taskInfoTable').bootstrapTable({
            url: 'courier/taskInfo/page',
            queryParams : function (params) {
                return {
                    succFlag: $("input[name='succFlag']:checked").val(),
                    offset: params.offset,
                    limit: params.limit
                };
            },
            method: 'GET',
            contentType : "application/x-www-form-urlencoded",
            toolbar: "#toolbar",
            cache: false,
            pagination: true,
            sidePagination: "server",
            paginationLoop: false,
            strictSearch: true,
            pageNumber:1,
            pageSize: 10,
            pageList: [10, 20, 50, 100],
            showColumns: true,
            minimumCountColumns: 2,
            showRefresh: true,
            searchOnEnterKey: true,
            uniqueId: "id",
            onClickRow: function (row, $element) {
                $('.info').removeClass('info');
                $($element).addClass('info');
            },
            columns: [{
                checkbox: true,
                visible: true
            }, {
                field: 'id',
                title: 'ID',
                align: 'center'
            }, {
                field: 'courierName',
                title: 'CourierName',
                align: 'center',
                formatter : function(value) {
                    var arr = value.split(".");
                    return "<span title='" + value + "'>" + arr[arr.length-1] + "</span>";
                }
            }, {
                field: 'param',
                title: 'Param',
                align: 'center',
                formatter : function(value, row) {
                    var result = "";
                    if (null != value && "" !== value) {
                        var succFlag = $("input[name='succFlag']:checked").val();
                        if ('0' === succFlag && row.failTimes > 0) {
                            var dataCodeId = "dataCode" + row.id;
                            result = "<code id='" + dataCodeId + "' onclick='writeParam0(" + row.id + ")' data-toggle='modal' data-target='#paramModal0' style='cursor: pointer'>" + value + "..." + "</code>";
                        } else {
                            result = "<code onclick='writeParam(" + row.id + ")' data-toggle='modal' data-target='#paramModal' style='cursor: pointer'>" + value + "..." + "</code>";
                        }
                    }
                    return result;
                }
            }, {
                field: 'execTime',
                title: '预执行时间',
                align: 'center',
                formatter: dateFormatter
            }, {
                field: 'execServerIP',
                title: '执行服务器',
                align: 'center'
            }, {
                field: 'execEndTime',
                title: '执行结束时间',
                align: 'center',
                formatter: dateFormatter
            }, {
                field: 'execMillis',
                title: '执行耗时（毫秒）',
                align: 'center'
            }, {
                field: 'failTimes',
                title: '失败次数',
                align: 'center',
                formatter : function(value) {
                    var result = "";
                    var succFlag = $("input[name='succFlag']:checked").val();
                    if ('0' === succFlag && value > 0) {
                        result = "<span style='color: red'>" + value + "</span>";
                    } else {
                        result = "<span style='color: green'>" + value + "</span>";
                    }
                    return result;
                }
            }, {
                field: 'failMessage',
                title: '失败信息',
                align: 'center',
                formatter : function(value, row) {
                    var result = "";
                    if (null != value && "" !== value) {
                        result = "<code onclick='writeFailMessage(" + row.id + ")' data-toggle='modal' data-target='#failMessageModal' style='cursor: pointer'>" + value + "..." + "</code>";
                    }
                    return result;
                }
            }]
        });
    }

    function dateFormatter(value) {
        var result = "";
        if (null != value) {
            var date = new Date(value);
            var monthStr = addZero(date.getMonth() + 1);
            var dateStr = addZero(date.getDate());
            var hourStr = addZero(date.getHours());
            var minuteStr = addZero(date.getMinutes());
            var secondStr = addZero(date.getSeconds());
            result = date.getFullYear() + '-' + monthStr + '-' + dateStr + " " + hourStr + ":" + minuteStr + ":" + secondStr;
        }
        return result;
    }

    function addZero(value) {
        if (value < 10) {
            return "0" + value;
        }
        return value;
    }
    
    function execute() {
        var arr = $('#taskInfoTable').bootstrapTable('getSelections');
        if (arr.length > 0) {
            var ids = [];
            arr.forEach(function(item){
                ids.push(item.id);
            });

            $.ajax({
                url: "courier/taskInfo/execute",
                data: JSON.stringify(ids),
                contentType:"application/json",
                type: "POST",
                success: function() {
                    $('#taskInfoTable').bootstrapTable('refresh');
                },
                error:function() {
                    layer.alert("请求出错.", {title: '友情提示', icon: 0});
                }
            });
        } else {
            layer.alert("请至少选择一条数据.", {title: '友情提示', icon: 0});
        }
    }

    function writeParam0(id) {
        $.ajax({
            url: "courier/taskInfo/param?succFlag=0&id=" + id,
            type: "GET",
            success: function(data) {
                if (data) {
                    $("#taskInfoID").val(id);
                    var result = jsonFormat2(data, 4);
                    $("#paramTA").val(result);
                }
            },
            error:function() {
                layer.alert("请求出错.", {title: '友情提示', icon: 0});
            }
        });
    }

    function updateParam() {
        var newData0 = $("#paramTA").val();
        var newData = jsonFormat2(newData0, 0);
        if ("" !== newData) {
            var id = $("#taskInfoID").val();
            $.ajax({
                url: "courier/taskInfo/param/update",
                data: {
                    newData: newData,
                    id: id
                },
                type: "POST",
                success: function() {
                    $("#dataCode"+id).text(newData.substr(0, 20) + "...");
                    $('#paramModal0').modal('hide');
                },
                error:function() {
                    layer.alert("请求出错.", {title: '友情提示', icon: 0});
                }
            });
        }
    }

    function writeParam(id) {
        var succFlag = $("input[name='succFlag']:checked").val();
        $.ajax({
            url: "courier/taskInfo/param?succFlag=" + succFlag + "&id=" + id,
            type: "GET",
            success: function(data) {
                if (data) {
                    var result = jsonFormat2(data, 4);
                    $("#paramPre").text(result);
                }
            },
            error:function() {
                layer.alert("请求出错.", {title: '友情提示', icon: 0});
            }
        });
    }

    function writeFailMessage(id) {
        var succFlag = $("input[name='succFlag']:checked").val();
        $.ajax({
            url: "courier/taskInfo/failMessage?succFlag=" + succFlag + "&id=" + id,
            type: "GET",
            success: function(data) {
                if (data) {
                    var result = jsonFormat2(data, 4);
                    $("#failMessagePre").text(result);
                }
            },
            error:function() {
                layer.alert("请求出错.", {title: '友情提示', icon: 0});
            }
        });
    }

    function jsonFormatPTA(spaceNum) {
        var pta = $("#paramTA");
        var str = pta.val();
        var result = jsonFormat(str, spaceNum);
        if ("" !== result) {
            pta.val(result);
        }
    }

    function jsonFormat(str, spaceNum) {
        var result = "";
        if (typeof str === 'string') {
            try {
                var obj = JSON.parse(str);
                if (typeof obj === 'object' && obj) {
                    result = JSON.stringify(obj, null, spaceNum);
                } else {
                    layer.alert("JSON格式不正确.", {title: '友情提示', icon: 0});
                }
            } catch(e) {
                layer.alert("JSON格式不正确.", {title: '友情提示', icon: 0});
                console.log('error：'+str+'!!!'+e);
            }
        } else {
            console.log('It is not a string!');
        }
        return result;
    }

    function jsonFormat2(str, spaceNum) {
        if (typeof str === 'string') {
            try {
                var obj = JSON.parse(str);
                if (typeof obj === 'object' && obj) {
                    return JSON.stringify(obj, null, spaceNum);
                } else {
                    return str;
                }
            } catch(e) {
                return str;
            }
        }
        return str;
    }

</script>
<div class="modal fade" id="paramModal0" tabindex="-1" role="dialog" aria-labelledby="paramModalLabel0" aria-hidden="true">
    <div class="modal-dialog" style="width:960px">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                <h4 class="modal-title" id="paramModalLabel0">
                    Param　
                    <button type="button" class="btn btn-primary" onclick="jsonFormatPTA(4)">JSON格式化</button>　
                    <button type="button" class="btn btn-primary" onclick="jsonFormatPTA(0)">JSON压缩</button>
                </h4>
            </div>
            <div class="modal-body">
                <input type="hidden" id="taskInfoID">
                <label>
                    <textarea id="paramTA" class="form-control" style="width: 925px; height: 475px;"></textarea>
                </label>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" onclick="updateParam()">确认修改（-请慎重操作-）</button>
            </div>
        </div>
    </div>
</div>
<div class="modal fade" id="paramModal" tabindex="-1" role="dialog" aria-labelledby="paramModalLabel" aria-hidden="true">
    <div class="modal-dialog" style="width:960px">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                <h4 class="modal-title" id="paramModalLabel">Param</h4>
            </div>
            <div class="modal-body">
                <pre id="paramPre"></pre>
            </div>
        </div>
    </div>
</div>
<div class="modal fade" id="failMessageModal" tabindex="-1" role="dialog" aria-labelledby="failMessageModalLabel" aria-hidden="true">
    <div class="modal-dialog" style="width:960px">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                <h4 class="modal-title" id="failMessageModalLabel">错误信息</h4>
            </div>
            <div class="modal-body">
                <pre id="failMessagePre"></pre>
            </div>
        </div>
    </div>
</div>
</body>
</html>